<template>
  <div class="home-new" ref="target">
    <HomePanel title="新鲜好物" subTitle="新鲜出炉 品质靠谱">
      <template #right>
        <XtxMore path="/"></XtxMore>
      </template>
      <!-- 面板内容 -->
      <div style="height:406px ;overflow:hidden">
        <!-- 上面的div解决盒子一瞬间被撑开的效果 ，因为样式冲突造成的-->
        <transition name="fade">
          <ul class="goods-list" v-if="goods.length">
            <li v-for="item in goods" :key="item.id">
              <RouterLink :to="`/product/${item.id}`">
                <img :src="item.picture" alt="" />
                <p class="name ellipsis">{{ item.name }}</p>
                <p class="price">&yen;{{ item.price }}</p>
              </RouterLink>
            </li>
          </ul>
        </transition>
        <!-- 骨架屏 -->
        <transition name="fade">
          <HomeSkeleton v-if="goods.length === 0"></HomeSkeleton>
        </transition>
      </div>
    </HomePanel>
  </div>
</template>

<script>
import { ref } from 'vue'
import { HomeNew } from '@/api/home.js'
import HomePanel from './home-panel.vue'
import HomeSkeleton from './home-skeleton.vue'
import { useIntersectionObserver } from '@vueuse/core'
// 使用插件封装一个懒加载
function lazyLoad (fn) {
  const goods = ref([])
  const target = ref(null)
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      // console.log(isIntersecting)
      // targetIsVisible.value = isIntersecting
      if (isIntersecting) {
        // console.log(1)
        stop()
        fn().then(res => {
          goods.value = res.result
        })
      } else {
        // console.log(2)
      }
    }
  )
  return { goods, target }
}
export default {
  name: 'HomeNew',
  components: { HomePanel, HomeSkeleton },
  setup () {
    // HomeNew().then(res => {
    //   //   console.log(res.result)
    //   goods.value = res.result
    // })
    const { goods, target } = lazyLoad(HomeNew)
    return { goods, target }
  }
}
</script>

<style scoped lang="less">
.goods-list {
  display: flex;
  justify-content: space-between;
  height: 406px;
  li {
    width: 306px;
    height: 406px;
    background: #f0f9f4;
    .hoverShadow();
    img {
      width: 306px;
      height: 306px;
    }
    p {
      font-size: 22px;
      padding: 12px 30px 0 30px;
      text-align: center;
    }
    .price {
      color: @priceColor;
    }
  }
}
// .fade {
//   &-enter {
//     &-from {
//       opacity: 0;
//     }
//     &-active {
//       transition: all 0.5s;
//     }
//   }
//   &-leave {
//     &-to {
//       opacity: 0;
//     }
//     &-active {
//       transition: all 0.5s;
//     }
//   }
// }
</style>
